import _ from "lodash";
import { useEffect, useState } from "react";

const mid = _.debounce((pageName: string) => {
  window.location.href = pageName;
}, 500);

export const switchTab = (val: KeyboardEvent, pageName: string) => {
  if (val.key === "p" && val.ctrlKey) {
    val.preventDefault();
    mid(pageName);
  }
};

export const useHotKey = (keyType: string) => {
  const [active, setActive] = useState<number>(0);

  const keyPressed = (val: KeyboardEvent) => {
    if (val.key === keyType && val.ctrlKey) {
      val.preventDefault();
      setActive((val) => val + 1);
      return false;
    }
  };
  useEffect(() => {
    window.addEventListener("keydown", keyPressed, false);

    return () => {
      window.removeEventListener("keydown", keyPressed, false);
    };
  }, []);

  return active;
};
